package com.huatai.paas.controller;

import com.huatai.common.api.R;
import com.huatai.paas.dto.BackChunkDto;
import com.huatai.paas.service.FileChunkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.*;

@RestController
@RequestMapping("/upload")
public class FileUploadNgController {

	private static final String UPLOAD_DIR = "/path/to/upload/directory";

	@Autowired
	private FileChunkService fileChunkService;

//	@Value("${file.upload-dir}")
//	private String uploadDir;

	@PostMapping("/chunk")
	public R<Integer> uploadChunk(@ModelAttribute BackChunkDto backChunkDto) {
		try {
			// 获取文件流和分片信息
			MultipartFile file = backChunkDto.getFile();
			int chunkNumber = backChunkDto.getChunkNumber();
			long totalChunks = backChunkDto.getTotalChunks();
			String fileName = backChunkDto.getFileName();
			String identifier = backChunkDto.getIdentifier();

			// 构造文件分片的临时保存路径
			File chunkFile = new File(UPLOAD_DIR + "/chunks/" + identifier + "_chunk_" + chunkNumber);
			file.transferTo(chunkFile);  // 保存分片

			// 如果是最后一个分片，合并所有分片
			if (chunkNumber == totalChunks - 1) {
				mergeChunks(identifier, totalChunks, fileName);
			}
			return null;
//			return R.data(fileChunkService.postFileUploadMinio(chunk, response));
		} catch (IOException e) {
			e.printStackTrace();
			return R.fail("上传失败");
		}
	}

	private void mergeChunks(String identifier, long totalChunks, String fileName) {
		try {
			// 合并所有分片
			FileOutputStream outputStream = new FileOutputStream(UPLOAD_DIR + "/final_files/" + fileName);
			for (int i = 0; i < totalChunks; i++) {
				File chunkFile = new File(UPLOAD_DIR + "/chunks/" + identifier + "_chunk_" + i);
				Files.copy(chunkFile.toPath(), outputStream);
				chunkFile.delete(); // 删除已合并的分片
			}
			outputStream.close();
			System.out.println("File merge complete!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
